package com.expmle.surfaceviewdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Looper;
import android.util.Log;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池学习使用
 */
public class ThreadPoolActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "ThreadPoolActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread_pool);

        // 线程池，保证线程以队列方式一个一个执行，不出现内存溢出
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(this);
        executorService.execute(this);
        executorService.execute(this);


        ExecutorService executorFixedThreadPool = Executors.newFixedThreadPool(2);
        executorFixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadPoolActivity.run ypk1");
            }
        });
        executorFixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadPoolActivity.run ypk2");
            }
        });
        executorFixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadPoolActivity.run ypk3");
            }
        });
        executorFixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadPoolActivity.run ypk4");
            }
        });

        System.out.println("ThreadPoolActivity.onCreate" + executorFixedThreadPool);


        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        //延迟三秒执行
        scheduledExecutorService.schedule(this, 3, TimeUnit.SECONDS);


    }

    int i = 0;

    @Override
    public void run() {
        System.out.println("ThreadPoolActivity.run i=" + i++);
    }

    public static boolean isInMainThread() {
        Looper myLooper = Looper.myLooper();
        Looper mainLooper = Looper.getMainLooper();
        Log.i(TAG, "isInMainThread myLooper=" + myLooper + ";mainLooper=" + mainLooper);
        return myLooper == mainLooper;
    }

}
